package com.hae.cloud.testorderservice.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping
public class RibbonProtoController {

    //请求数
    private int reqCount;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/getUserByDefineRibbon")
    public String getUsers() {
        //获取远程服务地址
        String url = getRemoteUrl() + "getUser";
        System.out.println(url);

        //通过httpClient进行远程调用，由于已经获得具体地址，所以不用使用LoadBalanced注解restTemplate
        String result = restTemplate.getForObject(url, String.class);

        //输出并返回
        System.out.println("会员服务调用订单服务,result:" + result);
        return result;

    }

    /**
     * 根据服务名称和请求数，从服务集群中获取远程服务地址
     * @return
     */
    private String getRemoteUrl() {
        String remoteUrl = null;
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("app-hae-member");
        //查询结果不空时才进行取之，可以考虑将serviceInstances缓存起来，当查询为空时从缓存中取得。
        if (null != serviceInstances && serviceInstances.size() > 0) {
            int random = reqCount%serviceInstances.size(); //此处可能有线程安全问题，可以采用auto原子计数器，它采用cas无锁机制，效率较高
            remoteUrl = serviceInstances.get(random).getUri().toString();
        }
        reqCount++;
        return remoteUrl;
    }
}
